<template>
  <div>
    <PageContent
      :list="list"
      :total-count="totalCount"
      :page="pagination.page"
      v-bind="ContentConfig"
      @currentChange="currentChange"
      @SizeChange="SizeChange"
    >
      <template v-if="meta.indexOf('CoinsGoodsSave') > -1" #header>
        <el-button
          v-if="meta.indexOf('CoinsGoodsSave') > -1"
          v-preventReClick
          type="primary"
          @click="addAndEdit()"
        >
          {{ $t('message.xinjian') }}
        </el-button>
      </template>
      <!-- 2.列中的插槽 -->
      <template #image="scope">
        <el-image
          style="width: 42px"
          :src="scope.row.picUrl"
          :preview-src-list="[scope.row.picUrl]"
        />
      </template>
      <template #status="scope">
        <el-switch
          v-model="scope.row.status"
          active-value="1"
          inactive-value="0"
          :disabled="meta.indexOf('CoinsGoodsDel') === -1"
          @change="statusChange(scope.row)"
        />
      </template>
      <template #handler="scope">
        <div class="flex-cc">
          <el-button
            v-if="meta.indexOf('CoinsGoodsUpdate') > -1"
            type="text"
            @click="handleEditClick(scope.row)"
          >
            {{ $t('message.edit') }}
          </el-button>
          <el-button
            v-if="meta.indexOf('CoinsGoodsDel') > -1"
            type="text"
            class="danger"
            @click="handleDeleteClick(scope.row)"
          >{{ $t('message.del') }}</el-button>
        </div>
      </template>
    </PageContent>
    <el-dialog
      :title="ModalTitle"
      :visible.sync="isShowModal"
      :close-on-click-modal="closeModal"
      :close-on-press-escape="closeModal"
      width="600px"
    >
      <el-form
        ref="form"
        class="doumee-form"
        :model="param"
        :rules="setRules"
        label-width="auto"
        label-suffix="："
      >
        <el-form-item :label="$t('message.ky')" class="select-style" prop="pic" :rules="{ required: true, message: param.code == 'coinsZero' ? $t('message.qsc') + $t('message.ky'):$t('message.qxz') + $t('message.ky'), trigger: 'change' }">
          <el-radio-group v-model="param.code" @change="changeType">
            <el-radio v-for="(item, index) in memberImgList" :key="index" :label="item.code">{{ item.remaks }}</el-radio>
          </el-radio-group>
          <transition name="fade">
            <Cropper
              v-if="dialogCropperVisible"
              :option-img="optionImg"
              :fileinfo="fileinfo"
              use-type="COIN_IMG"
              :fixed-number="[100,100]"
              @formSubmit="cropperSubmit"
              @formClose="cropperClose"
            />
          </transition>
          <div class="upload-wrap">
            <el-upload
              v-if="param.code == 'coinsZero'"
              class="device-uploader"
              :action="uploadFileUrl"
              :data="uploadParam"
              :show-file-list="false"
              accept=".jpg,.png,.jpeg"
              :auto-upload="false"
              :on-change="addFileChange"
            >
              <img
                style="width: 84px; height: 84px"
                src="@/assets/images/btn_uploadcard.png"
                alt=""
              >
              <div
                v-show="param.showPic"
                class="file"
                :style="'background-image: url(' + param.showPic + ')'"
              >
                <div class="delete">
                  <i class="el-icon-delete icon" @click.stop="deleteImage" />
                </div>
              </div>
            </el-upload>
          </div>
          <el-image
            v-if="param.code != 'coinsZero' && param.showPic"
            style="width: 84px; height: 84px"
            :src="param.showPic"
            :preview-src-list="[param.showPic]"
          />
        </el-form-item>
        <el-form-item :label="$t('message.bsl')" prop="coinNum">
          <el-input
            v-model="param.coinNum"
            :placeholder="$t('message.qsrbdsldw')"
            oninput="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"
            @change="coinNumChange"
          />
        </el-form-item>
        <el-form-item :label="$t('message.price')" prop="price">
          <el-input
            v-model="param.price"
            :placeholder="$t('message.qsrjgdw')"
            oninput="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"
          />
        </el-form-item>
        <el-form-item :label="$t('message.spmc')" prop="name">
          <el-input
            v-model="param.name"
            :placeholder="$t('message.qsr') + $t('message.spmc')"
          />
        </el-form-item>
        <el-form-item :label="$t('message.sort2')" prop="sortNum">
          <el-input
            v-model="param.sortNum"
            :placeholder="$t('message.qsr') + $t('message.sort2')"
            oninput="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"
          />
        </el-form-item>
        <el-form-item :label="$t('message.zjzt')">
          <el-switch
            v-model="param.status"
            active-value="1"
            inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShowModal = false">{{ $t('message.qx') }}</el-button>
        <el-button
          v-preventReClick
          type="primary"
          :loading="subLoading"
          @click="onSubmit"
        >{{ $t('message.qr') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import PageContent from '../pagecContent'
import Cropper from '@/components/cropper'

import { ContentConfig } from '../setSellConfig'
import { setRules } from './config'
import { uploadFile, coinsGoodslist, coinsGoodsAdd, coinsGoodsEdit, coinsGoodsDel, coinsGoodsUpdate, coinsGoodsPicList } from '@/api'
export default {
  components: {
    PageContent,
    Cropper
  },
  props: {
    meta: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      ContentConfig,
      list: [],
      loadLoading: false,
      pagination: {
        page: 1,
        rows: 10
      },
      totalCount: 0,

      isShowModal: false,
      subLoading: false,
      param: {},
      closeModal: this.$store.getters.dialog,
      ModalTitle: this.$t('message.xjshbpz'),
      setRules,
      optionImg: '',
      memberImgList: [],
      fileinfo: {},
      dialogCropperVisible: false,
      uploadFileUrl: uploadFile,
      uploadParam: {
        folder: 'COIN_IMG'
      }
    }
  },
  created() {
    this.handleQuery()
  },
  methods: {
    handleQuery() {
      this.pagination.page = 1
      this.getList()
    },
    async getList() {
      const { pagination } = this
      this.listLoading = true
      try {
        const res = await coinsGoodslist({ pagination, param: {}})
        this.list = res.recordList
        this.totalCount = res.totalCount
      } catch (err) {
        console.log('error')
      } finally {
        this.listLoading = false
      }
    },
    addAndEdit() {
      this.param = {
        status: '0'
      }
      this.ModalTitle = this.$t('message.xjshbpz')
      this.getMrMemberImg()
      this.isShowModal = true
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
    },
    onSubmit() {
      const { param } = this
      param.isNormal = param.code === 'coinsZero' ? '0' : '1'
      let fn, message
      if (param.id) {
        fn = coinsGoodsEdit
        message = this.$t('message.editcg')
      } else {
        fn = coinsGoodsAdd
        message = this.$t('message.addcg')
      }
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.subLoading = true
          fn({ param }).then(res => {
            this.subLoading = false
            if (res.errorCode !== '000000') return
            this.$message.success(message)
            this.isShowModal = false
            this.handleQuery()
          }, () => {
            this.subLoading = false
          })
        }
      })
    },
    statusChange(item) {
      const { id, status } = item
      coinsGoodsUpdate({ param: { id, status }}).then(res => {
        this.handleQuery()
        if (res.errorCode !== '000000') return
        this.$message.success(this.$t('message.ztxgcg'))
      }, () => {
        this.handleQuery()
      })
    },
    currentChange(val) {
      this.pagination.page = val
      this.getList()
    },
    SizeChange(val) {
      this.pagination.rows = val
      this.getList()
    },
    handleEditClick(item) {
      console.log(item)
      this.param = { ...item }
      this.getMrMemberImg(item)
      this.ModalTitle = this.$t('message.xjshbpz')
      this.isShowModal = true
    },
    handleDeleteClick(item) {
      const that = this
      this.$confirm(this.$t('message.scpztc'), this.$t('message.ts'), {
        confirmButtonText: this.$t('message.qd'),
        cancelButtonText: this.$t('message.qx'),
        type: 'warning',
        callback: () => {},
        beforeClose: (action, ctx, close) => {
          if (action !== 'confirm') {
            close()
            return
          }
          ctx.confirmButtonLoading = true
          coinsGoodsDel({ param: { id: item.id }}).then(res => {
            ctx.confirmButtonLoading = false
            close()
            if (res.errorCode === '000000') {
              that.$message.success(this.$t('message.delcg'))
              that.handleQuery()
            }
          })
            .catch(() => { ctx.confirmButtonLoading = false })
        }
      }).finally(() => {})
    },
    handleModelEnter() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          alert('submit!')
        } else {
          console.log('error submit!!')
          return false
        }
      })
      // this.isShowModal = false
    },
    coinNumChange(val) {
      this.$set(this.param, 'name', val + this.$t('message.geibi'))
    },
    changeType(e) {
      if (e === 'coinsZero') {
        this.$set(this.param, 'pic', '')
        this.$set(this.param, 'showPic', '')
      } else {
        const arr = this.memberImgList
        arr.forEach(s => {
          if (s.code === e) {
            this.$set(this.param, 'pic', s.pic)
            this.$set(this.param, 'showPic', s.showPic)
          }
        })
      }
      this.$refs.form.clearValidate()
    },
    // 默认卡样式
    getMrMemberImg(row) {
      coinsGoodsPicList({ param: { type: 6 }}).then(res => {
        if (res.errorCode === '000000') {
          this.memberImgList = res.recordList || []
          if (this.memberImgList.length > 0) {
            if (row) {
              if (this.memberImgList.map(i => i.pic).indexOf(row.pic) === -1) {
                this.$set(this.param, 'code', 'coinsZero')
                this.$set(this.param, 'pic', row.pic)
                this.$set(this.param, 'showPic', row.picUrl)
              }
              this.memberImgList.forEach(item => {
                if (row.pic === item.pic) {
                  this.$set(this.param, 'code', item.code)
                  this.$set(this.param, 'pic', item.pic)
                  this.$set(this.param, 'showPic', item.showPic)
                }
              })
            } else {
              this.$set(this.param, 'code', res.recordList[0].code)
              this.$set(this.param, 'pic', res.recordList[0].pic)
              this.$set(this.param, 'showPic', res.recordList[0].showPic)
            }
          }
        }
      })
    },
    // 裁剪确定按钮
    cropperSubmit(config) {
      // preImg 完整路径  urlPre 不包含域名
      if (config.success) {
        this.$set(this.param, 'showPic', config.showUrl)
        this.$set(this.param, 'pic', config.insertUrl)
        this.dialogCropperVisible = false
        this.$refs.form.clearValidate()
      } else {
        this.$message.error(config.msg || this.$t('message.scsb'))
        this.$refs.form.clearValidate()
        this.dialogCropperVisible = false
      }
    },
    // 裁剪取消
    cropperClose() {
      this.dialogCropperVisible = false
    },
    async addFileChange(file, fileList) {
      // 上传，拿到file文件
      // this.files = file.raw;
      this.$nextTick(() => {
        this.optionImg = URL.createObjectURL(file.raw)
        this.fileinfo = file.raw
        this.dialogCropperVisible = true
      })
    },
    // 删除头像
    deleteImage() {
      this.$set(this.param, 'pic', '')
      this.$set(this.param, 'showPic', '')
    }
  }
}
</script>

<style lang="scss" scoped>
 @import "@/styles/variables.scss";
.device-uploader {
  width: 84px;
  height: 84px;
  display: flex;
  box-sizing: border-box;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  cursor: pointer;
  border: 1px dashed #ccc;
  border-radius: 8px;
  transition: all 0.3s;
  margin-right: 20px;
  &:hover {
    border-color: $menuActive;
    .uploader-icon {
      color: $menuActive;
    }
  }
  ::v-deep .el-upload {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    .file {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      background-size: contain;
      background-position: center;
      background-repeat: no-repeat;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      .delete {
        background-color: rgba(0, 0, 0, 0.5);
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        display: none;
        align-items: center;
        justify-content: center;
        .icon {
          color: #fff;
        }
      }
      &:hover {
        .delete {
          display: flex;
        }
      }
    }
  }
  .uploader-icon {
    color: #aaaaaa;
    font-size: 22px;
    transition: all 0.3s;
  }
}
</style>
